﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Media;
using System.Windows.Input;
using System.ComponentModel.Composition;
using Microsoft.Practices.ServiceLocation;
using DynamicUIFramework;

namespace DynamicUIFramework
{
    [TemplatePart(Name = "PART_DragThumb", Type = typeof(DragThumb))]
    [TemplatePart(Name = "PART_ResizeDecorator", Type = typeof(Control))]
    [TemplatePart(Name = "PART_ContentPresenter", Type = typeof(ContentPresenter))]
    [Serializable]
    public class DesignerItem : ContentControl, ISelectable
    {
        public DesignerItem()
        {
            this.Loaded += new RoutedEventHandler(DesignerItem_Loaded);
            IsInDesignMode = DesignerContext.IsInDesignMode;
            if (DesignerContext.IsInDesignMode)
            {
                this.ContextMenu = new ContextMenu();
                MenuItem remove = new MenuItem { Header = "移除" };
                this.ContextMenu.Items.Add(remove);
                remove.Click += (s, e) =>
                {
                    MessageBoxResult result = MessageBox.Show("确定移除当前对象?", "移除", MessageBoxButton.OKCancel, MessageBoxImage.Warning, MessageBoxResult.Cancel);
                    if (result == MessageBoxResult.OK)
                    {
                        if (this.Content != null)
                        {
                            object parent = VisualTreeHelper.GetParent(this);
                            Panel p = parent as Panel;
                            if (p != null)
                            {
                                if (p.Children.Contains(this))
                                    p.Children.Remove(this);
                            }
                        }
                    }
                };
            }
        }

        protected override void OnContentChanged(object oldContent, object newContent)
        {
            base.OnContentChanged(oldContent, newContent);
            if (DesignerContext.IsInDesignMode)
            {
                MenuItem mi = null;
                foreach (var item in this.ContextMenu.Items)
                {
                    string name = (item as MenuItem).Name;
                    if (name == "__property")
                    {
                        mi = item as MenuItem;
                        break;
                    }
                }
                if (mi != null)
                    this.ContextMenu.Items.Remove(mi);

                if (this.Content is IElement)
                {
                    MenuItem __property = new MenuItem { Header = "属性" };
                    __property.Click += (s, e) =>
                    {
                        if (this.Content is IElement)
                        {
                            PropertyDialog pd = new PropertyDialog();
                            pd.Target = this.Content as IElement;
                            pd.ShowDialog();
                        }
                    };
                    this.ContextMenu.Items.Add(__property);
                }
            }
        }
        
        void DesignerItem_Loaded(object sender, RoutedEventArgs e)
        {
            if (DesignerContext.IsInDesignMode == false)
                return;

            if (base.Template != null)
            {
                ContentPresenter contentPresenter =
                    this.Template.FindName("PART_ContentPresenter", this) as ContentPresenter;
                if (contentPresenter != null)
                {
                    contentPresenter.IsHitTestVisible = false;
                    UIElement contentVisual = VisualTreeHelper.GetChild(contentPresenter, 0) as UIElement;
                    if (contentVisual != null)
                    {
                        DragThumb thumb = this.Template.FindName("PART_DragThumb", this) as DragThumb;
                        if (thumb != null)
                        {
                            ControlTemplate template =
                                DesignerItem.GetDragThumbTemplate(contentVisual) as ControlTemplate;
                            if (template != null)
                                thumb.Template = template;
                        }
                    }
                }
            }
        }

        public bool IsSelected
        {
            get { return (bool)GetValue(IsSelectedProperty); }
            set { SetValue(IsSelectedProperty, value); }
        }
        public static readonly DependencyProperty IsSelectedProperty =
          DependencyProperty.Register("IsSelected",
                                       typeof(bool),
                                       typeof(DesignerItem),
                                       new FrameworkPropertyMetadata(false));

        public bool IsInDesignMode
        {
            get { return (bool)GetValue(IsInDesignModeProperty); }
            set { SetValue(IsInDesignModeProperty, value); }
        }
        public static readonly DependencyProperty IsInDesignModeProperty =
          DependencyProperty.Register("IsInDesignMode",
                                       typeof(bool),
                                       typeof(DesignerItem),
                                       new FrameworkPropertyMetadata(false));

        public static readonly DependencyProperty DragThumbTemplateProperty =
            DependencyProperty.RegisterAttached("DragThumbTemplate", typeof(ControlTemplate), typeof(DesignerItem));

        public static ControlTemplate GetDragThumbTemplate(UIElement element)
        {
            return (ControlTemplate)element.GetValue(DragThumbTemplateProperty);
        }
        
        public static void SetDragThumbTemplate(UIElement element, ControlTemplate value)
        {
            element.SetValue(DragThumbTemplateProperty, value);
        }

        protected override void OnPreviewMouseDown(MouseButtonEventArgs e)
        {
            base.OnPreviewMouseDown(e);

            //if (DesignerContext.IsInDesignMode == false)
            //    return;

            Canvas designer = VisualTreeHelper.GetParent(this) as Canvas;

            // update selection
            if (designer != null)
                if ((Keyboard.Modifiers & (ModifierKeys.Shift | ModifierKeys.Control)) != ModifierKeys.None)
                    if (this.IsSelected)
                    {
                        this.IsSelected = false;
                    }
                    else
                    {
                        this.IsSelected = true;
                    }
                else if (!this.IsSelected)
                {
                    foreach (var item in designer.Children)
                    {
                        (item as DesignerItem).IsSelected = false;
                    }
                    this.IsSelected = true;
                }
            e.Handled = false;
        }
    }
}
